﻿//
// Created by Administrator on 2020/8/29.
//

#include "String.h"
#include <iostream>

int String::StrNum = 0;

String::String(const char *content) {
    std::cout << "construct String" << std::endl;
    StrNum++;
    if (content == nullptr) {
        size = 0;
    } else {
        size = strlen(content);
        innerContent = new char[size + 1];
        std::strcpy(innerContent, content);
    }
}


String::String(const String &oStr) {
    std::cout << "copy construct String" << std::endl;
    StrNum++;
    if (oStr.innerContent == nullptr) {
        size = 0;
        innerContent = nullptr;
    } else {
        size = oStr.size;
        innerContent = new char[size + 1];
        std::strcpy(this->innerContent, oStr.innerContent);
    }
}

String &String::operator=(const String &oStr) {
    std::cout << "assign construct String" << std::endl;
    if (&oStr == this) {
        return *this;
    }
    delete[] innerContent;
    if (oStr.innerContent == nullptr) {
        size = 0;
        innerContent = nullptr;
    } else {
        size = oStr.size;
        innerContent = new char[size + 1];
        std::strcpy(this->innerContent, oStr.innerContent);
    }
    return *this;
}

String::~String() {
    std::cout << "deconstruct String" << std::endl;
    StrNum--;
    delete[] this->innerContent;
}

std::ostream &operator<<(std::ostream &os, const String &str) {
    if (str.innerContent != nullptr) {
        os << str.innerContent;
    }
    return os;
}